<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getEmployeesList } from '@/api/employees'
import { getDepartment, getDepartmentById, updateDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: false
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // code部门编码做深度校验
    const validCode = (rule, value, callback) => {
      let codeList = []
      if (this.isEdit) {
      // 编辑状态下
      // 过滤掉除了自己以外的部门，遍历编码，获得所有部门编码
        codeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      } else {
      // 添加状态下
        codeList = this.originList.map(item => item.code)
      }
      if (codeList.includes(value)) {
        callback(new Error(value + '已存在'))
      } else {
        callback()
      }
    }
    // 添加的模块的部门名字在同级部门中不允许重复
    const validName = (rule, value, callback) => {
      let nameList = null
      if (this.isEdit) {
        const pid = this.originList.find(item => item.id === this.id).pid
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.id).map(({ name }) => name)
      } else {
        nameList = this.originList.filter(item => item.pid === this.id).map(({ name }) => name)
      }
      if (nameList.includes(value)) {
        callback(new Error(value + '已存在'))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2~10位字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }

        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2~10位字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门管理人', trigger: 'change' }

        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 2, max: 300, message: '请输入2~300位字符', trigger: 'blur' }
        ]

      },
      employees: []
    }
  },
  created() {
    this.loadEmployees()
    this.loadDepartmentById()
  },
  methods: {
    // 根据id获取员工详情
    async loadDepartmentById() {
      if (!this.isEdit) return
      const res = await getDepartmentById(this.id)
      // console.log(res)
      // 数据回填
      this.form = res.data
    },
    // 获取员工简单列表
    async loadEmployees() {
      try {
        const res = await getEmployeesList()
        // 复制到员工信息列表中
        console.log(res)
        this.employees = res.data
      } catch (e) {
        console.log(e)
      }
    },
    // 点击确定的时候，添加到组织架构中
    hSubmit() {
      // 做判断
      // 兜底校验
      this.$refs.deptForm.validate(valid => {
        if (!valid) return
        if (this.isEdit) {
          this.doEdit()
        } else {
          this.doAdd()
        }
      })
    },
    // 封装添加子部门的组件
    async doAdd() {
      try {
        const res = await getDepartment({ ...this.form, pid: this.id })
        this.$message.success(res.message)
        // 当添加完成后，关闭弹框，重新获取员工信息列表
        // 需要在父组件中完成，在子组件中触发
        this.$emit('success')
      } catch (e) {
        // console.log(e)
        this.$message.error(e.message)
      }
    },
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        this.$message.success(res.message)
        // 当编辑完成后，关闭弹框，重新获取员工信息列表
        // 需要在父组件中完成，在子组件中触发
        this.$emit('success')
      } catch (e) {
        // console.log(e)
        this.$message.error(e.message)
      }
    },
    hCancel() {
      // 清空表单
      this.$refs.deptForm.resetFields()
      this.$emit('hclose')
    }

  }
}
</script>
